package com.myandroid.contactadder;

import java.util.ArrayList;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.OnAccountsUpdateListener;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.RawContacts;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class ContactAdderActivity extends Activity implements OnAccountsUpdateListener {
    /** Called when the activity is first created. */
	private Spinner		mSpinner;
	private EditText	mNameText;
	private EditText	mPhoneText;
	private Button		mSaveButton;
	
	private ArrayAdapter<String>	mAdapter;
	private ArrayList<String>		mAccountList;
	private ArrayList<String>		mAccountTypeList;
	
	private int mSelectedAccountIndex = -1;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mSpinner			= (Spinner)findViewById(R.id.accountSelector);
        mNameText			= (EditText)findViewById(R.id.edit_name);
        mPhoneText			= (EditText)findViewById(R.id.edit_phone);
        mSaveButton			= (Button)findViewById(R.id.saveButton);
        
        mAccountList		= new ArrayList<String>();
        mAccountTypeList	= new ArrayList<String>();
        
        mAdapter			= new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, mAccountList);
        
        mSpinner.setAdapter(mAdapter);
        
        mSpinner.setOnItemSelectedListener(
        	new OnItemSelectedListener() {

        		@Override
				public void onItemSelected(AdapterView<?> parent, View view,
        									int position, long id) {
        			mSelectedAccountIndex = position;
        		}
        		
        		@Override
        		public void onNothingSelected(AdapterView<?> parent) {
        			//Do Nothing
        		}
        	}
        );
        
        mSaveButton.setOnClickListener(new OnClickListener() {
        	@Override
        	public void onClick(View v) {
        		createContacts();
        	}
        });        
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	AccountManager.get(this).addOnAccountsUpdatedListener(this, null, true);
    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	AccountManager.get(this).removeOnAccountsUpdatedListener(this);
    }
    
    @Override
    public void onAccountsUpdated(Account[] accounts) {
    	mAccountList.clear();
    	mAccountTypeList.clear();
    	
    	for(Account ac : accounts) {
    		mAccountList.add(ac.name);
    		mAccountTypeList.add(ac.type);
    	}
    	
    	mAdapter.notifyDataSetChanged();
    }
    
    private void createContacts() {
    	String name		= mNameText.getText().toString();
    	String phone	= mPhoneText.getText().toString();
    	
    	ArrayList<ContentProviderOperation> opList =
    										new ArrayList<ContentProviderOperation>();
    	
    	opList.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
    			.withValue(RawContacts.ACCOUNT_NAME, mAccountList.get(mSelectedAccountIndex))
    			.withValue(RawContacts.ACCOUNT_TYPE, mAccountTypeList.get(mSelectedAccountIndex))
    			.build());
    	
    	opList.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
    			.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
    			.withValue(ContactsContract.Data.MIMETYPE,
    						CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
    			.withValue(CommonDataKinds.StructuredName.DISPLAY_NAME, name)
    			.build());
    	
    	opList.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
    			.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
    			.withValue(ContactsContract.Data.MIMETYPE,
    						CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
    			.withValue(CommonDataKinds.Phone.NUMBER, phone)
    			.withValue(CommonDataKinds.Phone.TYPE,
    						CommonDataKinds.Phone.TYPE_HOME)
    			.build());
    	
    	try {
        	getContentResolver().applyBatch(ContactsContract.AUTHORITY, opList);
        	
        	Toast.makeText(this, "주소록이 생성되었습니다.", Toast.LENGTH_SHORT).show();
        	
        	clearFields();	
        }catch(Exception e) {
        	e.printStackTrace();
        }
    }
    
    private void clearFields() {
		mNameText.setText("");
		mPhoneText.setText("");
	}
}